<template>
    <div class="login-page">
      <el-card class="el-card">
        <template #header>黑马面经运营后台</template>
        <el-form :model="form" :rules="rules" ref="form">
          <el-form-item label="用户名：" prop="username">
            <el-input placeholder="请输入用户名" v-model="form.username"/>
          </el-form-item>
          <el-form-item label="密码：" prop="password">
            <el-input placeholder="请输入密码：" v-model="form.password"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="login">登录</el-button>
            <el-button @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 表单验证四大件： -->
        <!-- 1.form标签要绑定model属性：绑定的是表单收集的数据 -->
        <!-- 2.绑定rule规则 -->
        <!-- 3.表单域：el-form-item 要绑定prop属性 -->
        <!-- 4.表单控件：input select 等 要v-model双向绑定表单收集数据 -->
  </template>
  
  <script>
  import {login} from '@/api/user'
  export default {
    name: 'login-page',
    data(){
        return{
            form:{
                username:'',
                password:''
            },

            rules:{
                username:[
                    {required:true,message:"请输入用户名",trigger:'blur'},
                    {max:10,min:5,message:"字符长度在5-10之间",trigger:'blur'},
                ],

                password:[
                    {required:true,message:"请输入密码",trigger:'blur'},
                    { pattern: /^\w{5,11}$/, message: '请输入 5 到 10 位的密码', trigger: ['blur', 'change'] }
                ]
            }
        }
    },
    methods:{
        login(){
            // 表单验证
            // 1.获取表单：通过表单的ref属性来获取表单

            // 2.通过validate来验证

            this.$refs.form.validate(async(valid)=>{
                if(valid){
                    //调用vuex中的loginAction
                    await this.$store.dispatch('users/loginAction',this.form)
                    // console.log(res)
                    // console.log('登录成功')
                    this.$router.push('/')
                }else{
                    console.log('登录失败')
                    return false;
                }
            })
        },
        //重置
        reset(){
            this.$refs.form.resetFields()
        }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .el-card {
    width: 420px;
    margin: 0 auto;
    // 深度作用选择器   ::v-deep   /deep/
    ::v-deep .el-card__header {
      background: rgba(114,124,245,1);
      text-align: center;
      color: white;
    }
  }
  </style>